package com.ahao.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtils {
    private static DataSource dataSource = null;
    private static final Properties PROPERTIES = new Properties();
    private static final ThreadLocal<Connection> THREADLOCAL = new ThreadLocal<>();

    static {
        try {
            PROPERTIES.load(DBUtils.class.getResourceAsStream("/db.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(PROPERTIES);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DataSource getDataSource() {
        return dataSource;
    }
    public static Connection getConnection() {
        Connection connection = THREADLOCAL.get();
        if (connection == null) {
            Connection con = null;
            try {
                con = dataSource.getConnection();
                THREADLOCAL.set(con);
                return con;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }





    public static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
